<template>
  <div class="wrap-container">
    <div class="filter_box">
      <div class="filter_1">
        <div class="sel_box">
          <div class="sel_l">
            <div class="filter_label">区域选择</div>
            <el-cascader
              filterable
              clearable
              placeholder="请选择区域"
              :options="filteredOptions"
              v-model="addressId"
              @change="handleChange"
            ></el-cascader>
          </div>
          <div class="search">
            <el-input
              clearable
              v-model="queryParams.stadiumName"
              placeholder="搜索"
              prefix-icon="Search"
              @input="handleInput"
            ></el-input>
          </div>
        </div>
        <div class="district_box">
          <div class="filter_list">
            <div
              :class="['filter_li', { active_li: queryParams.districtId == item.value }]"
              v-for="item in districtList"
              :key="item.value"
              @click="changeDistrict(item.value)"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
      </div>
      <div class="filter_1">
        <div class="sel_box">
          <div class="sel_l">
            <div class="filter_label">场馆类型</div>
            <div class="filter_list">
              <div
                :class="['filter_li', { active_li: queryParams.type == item.dictValue }]"
                v-for="item in dictTypeList"
                :key="item.dictValue"
                @click="changeType(item.dictValue)"
              >
                {{ item.dictLabel }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-click="handleClick">
          <el-tab-pane
            :label="`${item.name} (${item.num})`"
            :name="item.id"
            v-for="item in tabsList"
            :key="item.id"
          ></el-tab-pane>
        </el-tabs>
        <el-button
          type="primary"
          class="del_btn"
          v-hasPermi="['sys:stadium:btn_open_update']"
          @click="handleDelete(1)"
          >批量删除</el-button
        >
      </div>
      <el-table v-loading="loading" :data="stadiumList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="场馆名称" prop="stadiumName" width="260" fixed>
          <template v-slot="{ row }">
            <div class="stadium_info" @click="handleDetail(row.id)">
              <el-image :src="row.imgUrl" class="stadium_img" fit="cover" />
              <div class="stadium_cont">
                <p class="stadium_name">{{ row.stadiumName }}</p>
                <p class="stadium_type">
                  <span>场馆类型</span>
                  <img src="@/assets/images/icon/right_icon.png" alt="" />
                  <span>{{ row.stadiumType }}</span>
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属机构" prop="enterpriseName" width="180" />
        <el-table-column label="场馆地址" prop="address" width="220" show-overflow-tooltip />
        <el-table-column label="营业状态" width="100">
          <template v-slot="{ row }">
            <div :class="['status', row.enable == 1 ? 'status_green' : 'status_red']">
              <i class="dian"></i>
              <span>{{ row.enable == 1 ? '营业中' : '已停用' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="访问量" prop="businessLicenseNum" width="140">
          <template v-slot="{ row }">
            <p>预定量：{{ row.countAll }}</p>
            <p>浏览量：{{ row.countFoot }}</p>
          </template>
        </el-table-column>
        <el-table-column label="今日预约" prop="dayCount" width="120" />
        <el-table-column label="空闲时段" prop="dayResidue" width="120" />
        <el-table-column label="最近预约" prop="lastOrderTime" width="150" :formatter="formatter" />
        <el-table-column label="付款金额(元)" prop="sumMoney" width="150" :formatter="formatter" />
        <el-table-column label="操作" width="140" fixed="right">
          <template v-slot="{ row }">
            <div class="table_btn">
              <el-button
                type="text"
                class="primary_text"
                v-hasPermi="['sys:stadium:btn_view']"
                @click="handleDetail(row.id)"
                >详情</el-button
              >
              <el-button
                v-hasPermi="['sys:stadium:btn_remove']"
                type="text"
                @click="handleDelete(0, row.id)"
                >删除</el-button
              >
              <el-button
                type="text"
                v-hasPermi="['sys:stadium:btn_open_update']"
                @click="handleEnable(row.id, 0)"
                v-if="row.enable == 1"
                >停用</el-button
              >
              <el-button
                type="text"
                v-hasPermi="['sys:stadium:btn_open_update']"
                @click="handleEnable(row.id, 1)"
                v-if="row.enable == 0"
                >启用</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  listStadium,
  delStadium,
  editEnable,
  getAreaTree,
  countStadiumEnable,
} from '@/api/stadium/stadium'
import { listData } from '@/api/system/dict/data'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型
interface AreaItem {
  value: string
  label: string
  children?: AreaItem[]
}

interface DictItem {
  dictValue: string
  dictLabel: string
}

interface StadiumItem {
  id: number
  imgUrl: string
  stadiumName: string
  stadiumType: string
  enterpriseName: string
  address: string
  enable: number
  countAll: number
  countFoot: number
  dayCount: number
  dayResidue: number
  lastOrderTime: string
  sumMoney: number
}

interface TabsItem {
  id: string
  name: string
  num: number
}

interface QueryParams {
  pageNum: number
  pageSize: number
  stadiumName: string
  stateId: string
  cityId: string
  districtId: string
  type: string
  enable: string
}

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 总条数
const total = ref(0)
// 场馆表格数据
const stadiumList = ref<StadiumItem[]>([])
// 查询参数
const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  stadiumName: '',
  stateId: '10000009',
  cityId: '10000107',
  districtId: '',
  type: '',
  enable: '',
})
const areaTree = ref<AreaItem[]>([]) //省市区列表
const addressId = ref(['10000009', '10000107'])
const districtList = ref<AreaItem[]>([]) //根据省市id获取区县列表
const tabsList = ref<TabsItem[]>([
  { id: '-1', name: '全部', num: 0 },
  { id: '1', name: '营业中', num: 0 },
  { id: '0', name: '已停用', num: 0 },
])
const tabsVal = ref('-1')
const dictTypeList = ref<DictItem[]>([])
const multipleSelection = ref<StadiumItem[]>([]) //表格多选的值

const router = useRouter()

const filteredOptions = computed(() => {
  return areaTree.value.map((item) => ({
    ...item,
    children: item.children
      ? item.children.map((child) => ({ ...child, children: undefined }))
      : undefined,
  }))
})

// 获取省市区列表
const getArea = async () => {
  const res = await getAreaTree()
  areaTree.value = res.data
  getDistrictsByCityId(queryParams.cityId)
}

// 选择省市
const handleChange: Fn = (val: string[]) => {
  if (val && val.length >= 2) {
    if (val[0] !== undefined) {
      queryParams.stateId = val[0]
    }
    if (val[1] !== undefined) {
      queryParams.cityId = val[1]
    }
    districtList.value = []
    getDistrictsByCityId(queryParams.cityId)
    getList()
    getCount()
  }
}

// 根据市 ID 获取区县列表
const getDistrictsByCityId = (cityId: string) => {
  const city = areaTree.value
    .flatMap((province) => province.children || [])
    .find((city) => city.value === cityId)

  if (city && city.children) {
    districtList.value = [...city.children]
    districtList.value.unshift({ label: '不限', value: '' })
  }
}

//获取场馆类型
const getDictTypeList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 99,
    dictType: 'site_type',
  }
  const res: any = await listData(params)
  dictTypeList.value = res.rows
  dictTypeList.value.unshift({ dictValue: '', dictLabel: '综合' })
}

// 获取场馆启用/停用数量
const getCount = async () => {
  const { data } = await countStadiumEnable(queryParams)
  if (tabsList.value[0]) tabsList.value[0].num = data.countAll || 0
  if (tabsList.value[1]) tabsList.value[1].num = data.countQy || 0
  if (tabsList.value[2]) tabsList.value[2].num = data.countTy || 0
}

/** 查询场馆列表 */
const getList = async () => {
  loading.value = true
  const res: any = await listStadium(queryParams)
  stadiumList.value = res.rows
  total.value = res.total
  loading.value = false
}

// 表格tabs切换
const handleClick = () => {
  queryParams.enable = tabsVal.value == '-1' ? '' : tabsVal.value
  queryParams.pageNum = 1
  getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 场馆名称搜索
const handleInput = () => {
  handleQuery()
}

// 选择区筛选列表
const changeDistrict = (val: string) => {
  queryParams.districtId = val
  handleQuery()
}

// 选择类型筛选列表
const changeType = (val: string) => {
  queryParams.type = val
  handleQuery()
}

// 表格多选
const handleSelectionChange = (val: StadiumItem[]) => {
  multipleSelection.value = val
}

// 查看详情
const handleDetail = (id: number) => {
  router.push({ path: '/stadium/detail', query: { id: String(id) } })
}

// 删除按钮操作
const handleDelete = (type: number, id?: number) => {
  let ids = ''
  if (type == 1) {
    ids = multipleSelection.value.map((item) => item.id).join(',')
  } else {
    ids = String(id)
  }
  if (ids == '') {
    ElMessage.error('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('是否确认删除选中的数据项？')
    .then(() => {
      return delStadium(ids)
    })
    .then(() => {
      getList()
      getCount()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

// 停/启 用场馆按钮操作
const handleEnable = (id: number, enable: number) => {
  ElMessageBox.confirm(`是否确认${enable == 0 ? '停用' : '启用'}选中的数据项？`)
    .then(() => {
      return editEnable(id, enable)
    })
    .then(() => {
      getList()
      getCount()
      ElMessage.success('操作成功')
    })
    .catch(() => {})
}

const formatter = (row: any, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}

onMounted(() => {
  getArea()
  getDictTypeList()
  getList()
  getCount()
})
</script>

<style lang="scss" scoped>
.filter_box {
  background: #fff;
  padding: 0 15px 20px;
  overflow: hidden;
  .filter_1 {
    margin-top: 15px;
    font-size: 14px;
  }
  .filter_list {
    display: flex;
    align-items: center;
    .filter_li {
      color: #a6a6a6;
      margin-right: 25px;
      cursor: pointer;
      &.active_li {
        color: #0988fb;
      }
    }
  }
  .sel_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 21px;
    .filter_label {
      margin-right: 33px;
    }
    :deep(.el-cascader) {
      .el-input__inner {
        border: none;
        padding: 0;
        color: #383838;
      }
      .el-input__suffix {
        right: 30px;
        color: #383838;
      }
    }
  }
  .sel_l {
    display: flex;
    align-items: center;
  }
  .search {
    :deep(.el-input) {
      width: 284px;
      .el-icon-search:before {
        font-size: 23px;
        color: #808080;
      }
      .el-input__prefix {
        left: 8px;
      }
      .el-input__inner {
        height: 37px;
        line-height: 37px;
        padding-left: 49px;
        border-radius: 8px;
      }
    }
  }
  .district_box {
    margin-left: 89px;
    margin-top: 5px;
  }
}
.tabs_box {
  position: relative;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 15px;
  :deep(.el-tabs) {
    flex: 1;
    .el-tabs__header {
      margin: 0;
    }
  }
  .del_btn {
    width: 90px;
    height: 35px;
    line-height: 35px;
    background: #2a82e4;
    border-radius: 6px;
    padding: 0;
    color: #fff;
    margin-left: 32px;
  }
}
:deep(.el-tabs) {
  .el-tabs__nav-wrap::after {
    height: 1px;
    background-color: #e5e5e5;
  }
  .el-tabs__active-bar {
    display: none;
  }
  .el-tabs__nav {
    padding-left: 12px;
  }
  .el-tabs__item {
    position: relative;
    padding: 0;
    font-size: 16px;
    color: #808080;
    height: 44px;
    line-height: 44px;
    margin: 0 19px;
    &:nth-child(2) {
      margin-left: 0;
    }
    &.is-active {
      color: #2a82e4;
      &::after {
        display: block;
        content: '';
        width: 56px;
        height: 2px;
        background: #2a82e4;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        margin: 0 auto;
      }
    }
  }
}
.table_box {
  background: #fff;
  margin-top: 15px;
  padding: 0 15px 27px;
  .stadium_info {
    cursor: pointer;
    display: flex;
    align-items: center;
    .stadium_img {
      width: 50px;
      height: 50px;
      border-radius: 8px;
      margin-right: 10px;
    }
    .stadium_name {
      font-size: 14px;
      line-height: 21px;
    }
    .stadium_type {
      color: #a6a6a6;
      line-height: 21px;
      margin-top: 6px;
      img {
        width: 6px;
        height: 11px;
        margin: 0 6px 0 14px;
      }
    }
  }
  .status {
    display: flex;
    align-items: center;
    .dian {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
    }
    &.status_green {
      color: #0fbd66;
      .dian {
        background: #0fbd66;
      }
    }
    &.status_red {
      color: #d43030;
      .dian {
        background: #d43030;
      }
    }
  }
}
</style>
